import React, {PureComponent} from 'react';
import ws from "../../ws";
import Wave from "../../wave-flv"
import ConfigPage from "./ConfigPage";
import {getChannelDetail} from "../../api/channel";
import {getCollectorList} from "../../api/collector";
import {Button, Modal} from "antd";
import flvjs from "flv.js"
import {flvUrl, wsAlarmCountUrl as alarmWsUrl, wsCompareUrl} from "../../api/request";
import HandleAlarm from "./HandleAlarm";

class Detail extends PureComponent {

  constructor(props) {
    super(props);
    this.lines = [];
    this.compareUrl = wsCompareUrl
    this.wsArray = [];
    this.channelId = "";
    this.videoWidth = 600
    this.flvPlayer = null
    this.state = {
      collectorUuid: "",
      channel: "",
      alarmNum: "",
      showHandleAlarm: false,
      url: '',
      mute: true,
      status: '',
      collectors: []
    };
  }

  removeAllLine = () => {
    this.lines.map(line => {
      line.remove()
    })
    this.lines = []
  }

  componentWillUnmount() {

    this.unMountAll()

    // console.log('unmount')
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (this.props.match.params.channelId !== nextProps.match.params.channelId) {
      // console.log('aaaaaaa')
      this.compareUrl = wsCompareUrl
      this.unMountAll()
      this.initPage(nextProps.match.params.channelId)
    }
    // window.location.reload()
    // this.props.history.replace('/Home/MonitoringList')

  }

  componentDidMount() {
    this.unMountAll()
    this.initPage()
    // this.props.history.replace('/Home/MonitoringList')
  }

  initPage = (newChannelId) => {
    this._connectWsUnHandleAlarm();
    // this.channelId = this.props?.location?.query?.channelId

    this.channelId = newChannelId ?? this.props.match.params.channelId
    // console.log(123, this.channelId);
    if (this.channelId) {
      this.compareUrl += `channel_id=${this.channelId}`;
      getChannelDetail(this.channelId).then(res => {
        this.setState({
          channel: {
            ...res, nodes: res.nodes.map(node => ({
                ...node,
                name: node?.collector?.name,
                uuid: node?.collector?.uuid
              })
            )
          },
          url: `${flvUrl}/${res.nodes[0].collector?.uuid}`,
          collectorUuid: res.nodes[0].collector?.uuid
        }, () => {
          this._connectWsCompare(this.compareUrl);
          //设置视频播放器
        })
        getCollectorList({page: 1, pageSize: 10000, channelId: this.channelId}).then(res => {
          this.setState({
            collectorUuid: res.results[0].uuid,
            status: res.results[0].status,
            collectors: res.results
          })
          if (res.results[0].status !== 'idle') {
            this.initVideoPlayer()
          }
          this._initLines(this.state.channel.nodes_map)
        })
      });

      //获取要显示的节点
      return
    }
  }

  unMountAll = () => {
    this._closeAllWs();
    this.destroyFlvPlayer()
    this.removeAllLine()
    this.compareUrl = wsCompareUrl
  }

  initVideoPlayer = () => {
    if (this.state.channel?.channel_type === 'video' && this.state.status !== 'idle') {
      this.destroyFlvPlayer()
      this.flvPlayer = flvjs.createPlayer({
        type: 'flv',
        isLive: true,
        hasAudio: true,
        hasVideo: true,
        url: `${flvUrl}/${this.state.collectorUuid}`,
        enableWorker: false,
        lazyLoadMaxDuration: 3 * 60,
        seekType: 'range',
        withCredentials: false,
        cors: true
      })
      this.flvPlayer.on('error', (e) => {
        // console.log(e)
        // console.log('error', this.flvPlayer)
        this.destroyFlvPlayer()
      })
      const videoPlayer = document.getElementById("videoPlayer")
      this.flvPlayer.attachMediaElement(videoPlayer)
      this.flvPlayer.load()
    } else {
      this.setState({
        url: `${flvUrl}/${this.state.collectorUuid}`
      })
    }
  }

  destroyFlvPlayer = () => {
    // console.log('error', this.flvPlayer)
    if (this.flvPlayer) {
      this.flvPlayer.off('error', this.destroyFlvPlayer)
      this.flvPlayer.pause();
      this.flvPlayer.unload();
      this.flvPlayer.detachMediaElement();
      this.flvPlayer.destroy();
      this.flvPlayer = null;
    }
  }

//连接对比数据，并根据对比数据改变颜色
  _connectWsCompare = (compareUrl) => {
    ws.addConnect(compareUrl);
    ws[compareUrl].onmessage = event => {
      const compareRes = JSON.parse(event.data)

      // console.log('compare', compareRes);
      //获取有问题的section
      const noMatch = compareRes.filter((section) => {
        // console.log(section);
        return section.status === 'not_match'
        // return section.status === 'match'
      })
      // console.log(11111111111, this.lines)
      this.lines.map(line => {
        const {start, end} = line;
        // console.log(start.id);
        line.color = '#0f0'
        if (noMatch.length > 0) {
          noMatch.map((section, index) => {
            // console.log(section);
            if (start.id == section?.sample_node?.id && end.id == section?.meta_node?.id) {
              line.color = '#f00'
              noMatch.splice(index, 1)
              // console.log(noMatch)
            }
          })
        }
      })
    };
    this.wsArray.push(compareUrl)
  };

  _connectWsUnHandleAlarm = () => {
    // const alarmWsUrl = '/ws/levels_alarm_count/';
    ws.addConnect(alarmWsUrl);
    ws[alarmWsUrl].onmessage = event => {
      const unHandleAlarms = JSON.parse(event.data);
      unHandleAlarms.map(channel => {
        if (channel.id == this.channelId) {
          this.setState({
            alarmNum: channel.total_count
          })
        }
      })
    };
    this.wsArray.push(alarmWsUrl)
  };

  _closeAllWs() {
    console.log(this.wsArray)
    this.wsArray.map(item => {
      ws.deleteConnect(item)
    })
  }


  //初始化流向图
  _initLines = (nodesMap) => {
    nodesMap && nodesMap.map(node => {
      if (node.adjacency_nodes.length > 0) {
        const sNode = document.getElementById(node.node);
        // debugger
        node.adjacency_nodes.map(tId => {
          const tNode = document.getElementById(tId);
          const line = new window.LeaderLine(sNode, tNode, {path: 'grid', color: '#0f0'});
          line.position();
          this.lines.push(line)
        })
      }
    })
  };

  onChangeWaveId = uuid => () => {
    // console.log('onChangeWaveId', uuid);
    this.destroyFlvPlayer()
    this.setState({
      collectorUuid: uuid
    }, () => {
      this.initVideoPlayer()
    })
    this.getCollectorStatusByUUID(uuid)
    setTimeout(() => {
      this.lines.map(line => {
        line.position()
      })
    }, 0)

  };

  getCollectorStatusByUUID(uuid) {
    const {collectors} = this.state
    collectors.map((collector) => {
      if (collector.uuid === uuid) {
        this.setState({
          status: collector.status
        })
      }
    })
  }

  showHandleAlarm = () => {
    this.setState({showHandleAlarm: true})
    this.flvPlayer && this.flvPlayer.pause()
  }
  renderPlayer = () => {

    if (this.state?.channel && this.state?.status === 'active') {
      if (this.state?.channel?.channel_type === 'audio') {
        return (<Wave url={this.state.url} width={1100} colors={['#a459ff']} mute={this.state.mute}/>)
      } else {

        return (
          <video id={'videoPlayer'} width={this.videoWidth} height={this.videoWidth / 4 * 3}
                 controls autoPlay>
            当前浏览器不支持H5视频播放，请更换浏览器
          </video>
        )

      }
    } else if (this.state?.status === 'idle') {
      return (
        <div
          style={{
            width: '100%',
            height: '300px',
            lineHeight: '300px',
            fontSize: '34px',
            fontWeight: '600',
            textAlign: 'center',
            verticalAlign: 'middle'
          }}>信号中断，请检查线路！</div>
      )
    }

  }

  render() {
    const {channel} = this.state;
    return (
      <>
        <div style={{
          display: 'flex',
          flexDirection: 'column',
          background: '#fff',
          padding: '20px',
          width: '1140px',
        }}>
          <div style={{
            fontSize: '24px',
            width: '100%',
            display: 'flex',
            borderBottom: '1px solid #ccc',
            alignItems: 'center'
          }}>
            频道名称:
            <div style={{fontWeight: 600}}>{channel && channel.name}</div>
            <div style={{marginLeft: "auto"}}>异常数量:</div>
            <Button type="danger" style={{marginRight: '30px',}} onClick={this.showHandleAlarm}>
              {this.state.alarmNum}
            </Button>
            {
              this.state?.channel?.channel_type === 'audio' &&
              <Button type={this.state.mute ? "danger" : "primary"} style={{marginRight: '30px',}}
                      onClick={() => {
                        this.setState({
                          mute: !this.state.mute
                        })
                      }}>
                静音
              </Button>
            }
          </div>
          {/*<input type={'text'} value={'http://47.107.253.110/flv/52c0b255-3635-465a-8387-14ad5b37386a'}
                           onInput={(e) => {
                               console.log(e)
                           }}/>
                    <Button type={'primary'} onClick={() => {
                        this.destroyFlvPlayer()
                        this.setState({
                            url: 'http://47.107.253.110/flv/52c0b255-3635-465a-8387-14ad5b37386a'
                        }, () => {
                            this.initVideoPlayer()
                        })

                    }}>load</Button>*/}
          <div style={{padding: '10px 0', textAlign: 'center'}}>
            {
              this.renderPlayer()
            }
          </div>
          <div style={{width: `1100px`, height: '370px'}}>
            {
              channel && channel.nodes &&
              <ConfigPage
                canDrag={false}
                nodes={channel.nodes}
                onChangeWaveId={this.onChangeWaveId}
                collectorUuid={this.state.collectorUuid}
              />
            }
          </div>
        </div>
        <Modal
          title={channel?.name}
          visible={this.state.showHandleAlarm}
          destroyOnClose
          onCancel={() => {
            this.setState({
              showHandleAlarm: false
            })
          }}
          onOk={() => {
            this.setState({
              showHandleAlarm: false
            })
          }}
          width={'60%'}
        >
          <HandleAlarm channelId={channel?.id} channelUrl={this.state?.channel?.url}></HandleAlarm>
        </Modal>
      </>
    );
  }
}


export default Detail;
